package com.lib.common.sms;

import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import com.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * Created by ethan-liu on 2017/5/25.
 */
@Service
public class AlidayuSmsService implements SmsService {
    private static final Logger logger = LoggerFactory.getLogger(AlidayuSmsService.class);
    private static final SmsService INSTANCE = new AlidayuSmsService();

    @Value("${serverUrl}")
    private String serverUrl;
    @Value("${appKey}")
    private String appKey;
    @Value("${appSecret}")
    private String appSecret;

    private TaobaoClient client;

    private AlidayuSmsService() {
        this.client = new DefaultTaobaoClient(serverUrl, appKey, appSecret);
    }

    public static SmsService getInstance() {
        return INSTANCE;
    }

    private void send(AlibabaAliqinFcSmsNumSendRequest req) {
        try {
            AlibabaAliqinFcSmsNumSendResponse rsp = client.execute(req);
            logger.info(rsp.getBody());
        } catch (ApiException e) {
            logger.error("Error: ", e);
            throw new SmsException();
        }
    }

    @Override
    public void sendVerifyCode(String cellPhoneNum, String code) throws SmsException {
        AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
        req.setExtend("123456");
        req.setSmsType("normal");
        req.setSmsFreeSignName("安家喵");
        req.setSmsParamString("{\"code\":\"" + code + "\",\"product\":\"安家喵\"}");
        req.setRecNum(cellPhoneNum);
        req.setSmsTemplateCode("SMS_37675058");
        send(req);
    }

}